package cn.wolfcode.service.impl;

import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.domain.AccountLog;
import cn.wolfcode.domain.AccountTransaction;
import cn.wolfcode.domain.OperateIntergralVo;
import cn.wolfcode.mapper.AccountLogMapper;
import cn.wolfcode.mapper.AccountTransactionMapper;
import cn.wolfcode.mapper.UsableIntegralMapper;
import cn.wolfcode.service.IUsableIntegralService;
import cn.wolfcode.web.msg.IntergralCodeMsg;
import com.alibaba.fastjson.JSON;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;


@Service
public class UsableIntegralServiceImpl implements IUsableIntegralService {
    @Autowired
    private UsableIntegralMapper usableIntegralMapper;
    @Autowired
    private AccountTransactionMapper accountTransactionMapper;
    @Autowired
    private AccountLogMapper accountLogMapper;

    @Override
    @Transactional
    public Boolean alipayOnIntergral(OperateIntergralVo vo) {
        //1 添加积分变更日志
        AccountLog accountLog = new AccountLog();
        accountLog.setPkValue(vo.getPk());
        accountLog.setType(AccountLog.TYPE_DECR);
        accountLog.setAmount(vo.getValue());
        accountLog.setGmtTime(new Date());
        accountLog.setInfo(vo.getInfo());

        accountLogMapper.insert(accountLog);
        //2 付款，扣积分
        usableIntegralMapper.decrIntxergral(vo.getUserId(), vo.getValue());
        return true;


    }



    @Override
    @Transactional
    public Boolean refundOnIntegralTry(OperateIntergralVo vo, BusinessActionContext context) {
        //1 查询事务日志的记录
        String xid = context.getXid();
        String bid = String.valueOf(context.getBranchId());
        AccountTransaction accountTransaction = accountTransactionMapper.get(xid, bid);
        if (StringUtils.isEmpty(accountTransaction)) {
            //2 是null, 插入事务日志,状态是try,执行try逻辑
            //插入事务日志
            AccountTransaction transaction = new AccountTransaction();
            transaction.setTxId(xid);
            transaction.setActionId(bid);
            transaction.setUserId(vo.getUserId());
            transaction.setGmtCreated(new Date());
            transaction.setGmtModified(new Date());
            transaction.setAmount(vo.getValue());
            transaction.setType(String.valueOf(AccountLog.TYPE_INCR));
            transaction.setState(AccountTransaction.STATE_TRY);

            accountTransactionMapper.insert(transaction);
            //执行业务逻辑，  空操作

        } else if (accountTransaction.getState() == AccountTransaction.STATE_TRY) {
            //3 是try, 实现幂等,  啥也不做
        } else if (accountTransaction.getState() == AccountTransaction.STATE_COMMIT) {
            //4 是confirm, 抛异常
            throw new BusinessException(IntergralCodeMsg.OP_INTERGRAL_ERROR);
        } else {
            //5 是cancel,啥也不做(防悬挂)
        }
        return true;
    }

    @Override
    @Transactional
    public Boolean refundOnIntegralConfirm(BusinessActionContext context) {
        //1 查询事务日志的记录
        String xid = context.getXid();
        String bid = String.valueOf(context.getBranchId());
        AccountTransaction accountTransaction = accountTransactionMapper.get(xid, bid);
        //说去上下文中的vo对象
        String json = context.getActionContext().get("vo").toString();
        OperateIntergralVo vo = JSON.parseObject(json, OperateIntergralVo.class);

        Boolean ret = false;
        if (StringUtils.isEmpty(accountTransaction)) {
            //2 是null, 抛异常
            throw new BusinessException(IntergralCodeMsg.OP_INTERGRAL_ERROR);
        } else if (accountTransaction.getState() == AccountTransaction.STATE_TRY) {
            //3 是try, 执行业务逻辑 ,
            ret = refundOnIntegral(vo);
            //修改日志状态为confirm
            int m = accountTransactionMapper.updateAccountTransactionState(xid, bid, AccountTransaction.STATE_COMMIT,
                    AccountTransaction.STATE_TRY);
            if (m < 1) {
                throw new BusinessException(IntergralCodeMsg.OP_INTERGRAL_ERROR);
            }
        } else if (accountTransaction.getState() == AccountTransaction.STATE_COMMIT) {

            //4 是confirm, 实现幂等
        } else {
            //5 是cancel,抛异常
            throw new BusinessException(IntergralCodeMsg.OP_INTERGRAL_ERROR);
        }
        return ret;
    }

    @Override
    @Transactional
    public Boolean refundOnIntegralCancel(BusinessActionContext context) {
        //1 查询事务日志的记录
        String xid = context.getXid();
        String bid = String.valueOf(context.getBranchId());
        AccountTransaction accountTransaction = accountTransactionMapper.get(xid, bid);
        String json = context.getActionContext().get("vo").toString();
        OperateIntergralVo vo = JSON.parseObject(json, OperateIntergralVo.class);
        Boolean ret = true;
        if (StringUtils.isEmpty(accountTransaction)) {
            //2 是null, 插入一个事务日志,状态是cacel
            //插入事务日志
            AccountTransaction transaction = new AccountTransaction();
            transaction.setTxId(xid);
            transaction.setActionId(bid);
            transaction.setUserId(vo.getUserId());
            transaction.setGmtCreated(new Date());
            transaction.setGmtModified(new Date());
            transaction.setAmount(vo.getValue());
            transaction.setType(String.valueOf(AccountLog.TYPE_INCR));
            transaction.setState(AccountTransaction.STATE_CANCEL);

            accountTransactionMapper.insert(transaction);
            //执行业务逻辑，  空操作
        } else if (accountTransaction.getState() == AccountTransaction.STATE_TRY) {
            //3 是try, 执行业务逻辑 ,啥也不做
            //修改日志状态为cancel
            int m = accountTransactionMapper.updateAccountTransactionState(xid, bid, AccountTransaction.STATE_CANCEL,
                    AccountTransaction.STATE_TRY);
            if (m < 1) {
                throw new BusinessException(IntergralCodeMsg.OP_INTERGRAL_ERROR);
            }
        } else if (accountTransaction.getState() == AccountTransaction.STATE_COMMIT) {
            //4 是confirm, 抛异常
            throw new BusinessException(IntergralCodeMsg.OP_INTERGRAL_ERROR);

        } else {
            //5 是cancel, 实现幂等

        }
        return ret;
    }

    private Boolean refundOnIntegral(OperateIntergralVo vo) {
        //1 添加积分变更日志
        AccountLog accountLog = new AccountLog();
        accountLog.setPkValue(vo.getPk());
        accountLog.setType(AccountLog.TYPE_INCR);
        accountLog.setAmount(vo.getValue());
        accountLog.setGmtTime(new Date());
        accountLog.setInfo(vo.getInfo());

        accountLogMapper.insert(accountLog);
        //2 付款，扣积分
        usableIntegralMapper.addIntergral(vo.getUserId(), vo.getValue());
        return true;
    }
}
